const app = getApp()
var sliderWidth = 96

Page({
  data: {
    tishi: false,
    categoryList: [],
    activeIndex: 22,
    sliderOffset: 150,
    sliderLeft: 0,
    page: 1,
    videoList: [],
    imageUrl: app.globalData.imageUrl,
    flags: {},
    sysWidth: 0,
    isCollect: false,
    searchWord: "美女",
    inputValue: '', //搜索的内容
    collectList: [], // 收藏按钮列表
    navigateFlag: false,
    today: '',
  },

  onLoad: function () {
    var that = this
    that.setData({
      page: 1,
    })
    that.handleTishi()
    that.giftPaper()
    app.getAccInfo().then(function (res) {
      that.setData({
        navigateFlag: app.globalData.navigateFlag
      })
      if (app.globalData.navigateFlag) {
        wx.hideTabBar({})
        var myDate = new Date()
        that.setData({
          today: myDate.getFullYear() + '年' + myDate.getMonth() + 1 + '月' + myDate.getDate() + '日'
        })
      } else {
        wx.showLoading({
          title: '加载数据中...',
          success: function () {
            that.getConfig()
            that.getCategoryList()
            that.getRandomVideoByCateId(that.data.activeIndex)
          }
        })
        // 获取系统信息
        wx.getSystemInfo({
          success: res => {
            that.setData({
              sysWidth: res.windowWidth
            })
          }
        })
        that.getSearchWord()
      }
    })
  },

  getConfig: function () {
    var that = this
    wx.request({
      url: app.globalData.url + 'user/config?version=' + app.globalData.version,
      success: function (res) {
        if (res.data.data) {
          that.setData({
            flags: res.data.data
          })
        }
        if (!res.data.data.videoflag) {
          wx.setNavigationBarTitle({
            title: '美文欣赏',
          })
          wx.hideTabBar({})
        }
      }
    })
  },

  // 出纸活动
  giftPaper() {
    if (app.globalData.isGiftPaper) {
      let res = wx.getLaunchOptionsSync()
      if (res && res['query'] && res['query']['canshu'] && res['query']['dt'] && res['query']['openid']) {
        let equipment_no = res['query']['canshu']
        let dt = res['query']['dt']
        let chuzhi_openid = res['query']['openid']
        wx.request({
          url: 'https://api.xlqzh.com/xiaochengxu/chuzhi.aspx',
          data: {
            openid: chuzhi_openid,
            sbh: equipment_no,
            name: 'xyx',
            pass: 'xyx',
            dongzuo: 'put',
            dt: dt
          },
          header: {
            'content-type': 'application/json'
          },
          method: 'POST',
          dataType: 'json',
          success: (result) => {
            console.log(result)
            if (result && result.data == 'ok') {
              wx.showToast({
                title: '出纸成功',
                duration: 1500,
              })
            } else {
              wx.showToast({
                title: '出纸失败',
                icon: 'none',
                duration: 1500,
              })
            }
          },
        })
        app.globalData.isGiftPaper = false
        this.setData({
          activeIndex: 23
        })
      }
    }
  },

  // 处理提示
  handleTishi: function () {
    var that = this
    var tishi = wx.getStorageSync('haibao_tishi')
    if (!tishi) {
      that.setData({
        tishi: true
      })
      wx.setStorageSync('haibao_tishi', 1)
    }
  },

  // 获取分类列表
  getCategoryList: function () {
    var that = this
    wx.request({
      url: app.globalData.url + 'videos/get_category',
      data: {
        version: app.globalData.version
      },
      success: function (res) {
        var categoryList = res.data.data
        that.setData({
          categoryList: categoryList
        })
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              sliderLeft: (res.windowWidth / categoryList.length - sliderWidth) / 2,
            })
          }
        })
      }
    })
  },

  // 通过分类id获取视频列表
  getVideoListById: function (id) {
    var that = this
    var page = this.data.page
    var videoList = this.data.videoList
    wx.request({
      url: app.globalData.url + 'videos/get_videolist_by_category',
      data: {
        openid: app.globalData.openId,
        version: app.globalData.version,
        id: id,
        page: page
      },
      method: "POST",
      success: function (res) {
        var list = res.data.data
        if (list && list.length != 0) {
          that.setData({
            page: page + 1,
            videoList: videoList.concat(list),
          })
          for (let i = 0; i < list.length; i++) {
            that.setData({
              collectList: that.data.collectList.concat(list[i].favor)
            })
          }
          wx.hideLoading()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '已经到底了',
            icon: 'success',
            duration: 1000
          })
        }
      },
      fail: function (e) {
        console.log(e)
      }
    })
  },

  // tab点击事件
  tabClick: function (e) {
    // 页面跳到最上
    wx.pageScrollTo({
      scrollTop: 0,
    })
    var that = this
    var id = e.currentTarget.id
    this.setData({
      page: 1,
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: id
    })
    wx.showLoading({
      title: '加载数据中...',
      success: function () {
        that.getRandomVideoByCateId(parseInt(id))
        that.setData({
          collectList: []
        })
      },
    })
  },

  // 上拉加载
  onReachBottom: function () {
    var that = this
    var data = this.data
    wx.showLoading({
      title: '加载数据中...',
      success: function () {
        that.getVideoListById(parseInt(data.activeIndex))
      },
    })
  },

  // 获取formId
  formSubmit: function (e) {
    let formId = e.detail.formId
    let id = e.currentTarget.dataset.id
    if (app.globalData.isFirstOpen) {
      this.uploadFormid(formId)
    }
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id
    })
  },

  onShareAppMessage(res) {
    // 统计分享次数
    wx.request({
      url: app.globalData.url + 'user/handle_share',
      data: {
        openid: app.globalData.openId,
        video_id: res.target.dataset.id
      },
      method: 'POST',
      success: (res) => {
        wx.showToast({
          title: '分享成功',
          icon: 'none',
          image: '',
          duration: 1500,
          mask: false,
        })
      }
    })

    var sharetitle = res.target.dataset.title
    var id = res.target.dataset.id
    var cover = res.target.dataset.cover
    return {
      title: sharetitle,
      imageUrl: cover,
      path: '/pages/detail/detail?id=' + id,
    }
  },

  // 获取随机
  getRandom: function () {
    wx.pageScrollTo({
      scrollTop: 0,
    })
    var that = this
    var nowTap = that.data.activeIndex
    if (nowTap != 21) {
      that.getRandomVideoByCateId(parseInt(nowTap))
    } else {
      that.onLoad()
    }
  },

  // 根据分类id获取随机视频
  getRandomVideoByCateId: function (categoryId) {
    var that = this
    wx.request({
      url: app.globalData.url + 'videos/get_randomlist_by_category',
      data: {
        openid: app.globalData.openId,
        version: app.globalData.version,
        id: categoryId
      },
      method: "POST",
      success: function (res) {
        var list = res.data.data
        for (let i = 0; i < list.length; i++) {
          that.setData({
            collectList: that.data.collectList.concat(list[i].favor)
          })
        }
        that.setData({
          page: 1,
          videoList: list
        })
        wx.hideLoading()
      },
      fail: function (e) {
        console.log(e)
      }
    })
  },

  // 上传formid
  uploadFormid: function (formid) {
    var that = this
    //通过网络请求发送openid和formIds到服务器
    wx.request({
      // url: 'https://xcx.nanxuncn.cn/api/formid/save_formid',
      url: app.globalData.url + 'user/handler_formid',
      method: 'POST',
      data: {
        ghid: 'gh_91d384b2777f',
        openid: app.globalData.openId,
        formid: formid
      },
      success: function (res) {
        if (res.data.msg == 'ok') {
          app.globalData.isFirstOpen = false
        }
      }
    })
  },

  // 处理收藏逻辑
  collect: function (e) {
    var videoId = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    if (this.data.collectList[index]) {
      this.collectRequest(videoId, 'del')
    } else {
      this.collectRequest(videoId, 'add')
    }
  },
  // 判断是否收藏
  getIsCollect: function (videoId) {
    this.collectRequest(videoId, 'fetch')
  },
  // 收藏相关网络操作
  collectRequest: function (id, cType) {
    var that = this
    var url = app.globalData.url + 'user/'
    var isDel = true
    switch (cType) {
      case 'add':
        url = url + 'add_favor'
        break
      case 'del':
        url = url + 'del_favor'
        isDel = false
        break
      case 'fetch':
        url = url + 'fetch_favor'
        break
    }
    wx.request({
      url: url,
      method: 'POST',
      data: {
        version: app.globalData.version,
        openid: app.globalData.openId,
        video_id: id
      },
      success: function (res) {
        if (res.data.msg == 'ok') {
          let list = that.data.videoList
          for (let i = 0; i < list.length; i++) {
            if (list[i].id == id) {
              var nowitem = 'collectList[' + i + ']'
              that.setData({
                [nowitem]: isDel
              })
              return
            }
          }
        }
      }
    })
  },

  // 获取搜索默认词
  getSearchWord: function () {
    var that = this
    wx.request({
      url: app.globalData.url + 'videos/query_keyword',
      method: 'GET',
      success: (res) => {
        that.setData({
          searchWord: res.data.data,
          inputValue: res.data.data
        })
      },
    })
  },
  // 绑定搜索框的文本
  inputBind: function (event) {
    this.setData({
      inputValue: event.detail.value
    })
  },
  // 搜索
  search: function () {
    wx.navigateTo({
      url: '/pages/search/search?keyword=' + this.data.inputValue,
    })
  },

  // 跳转 集锦
  moveToMiniProgress: function () {
    wx.navigateToMiniProgram({
      appId: 'wx72da07ae39103a82'
    })
  },
})